﻿Imports DocumentFormat.OpenXml.Wordprocessing
Imports Ingr.RAD2D
Imports Llama
Imports Telerik.WinControls.UI

Public Class Result
    Dim dsResult As DataSet '用于在result.vb里 

    Sub New(ByRef _dsResult As DataSet)

        ' 此调用是设计器所必需的。
        InitializeComponent()

        ' 在 InitializeComponent() 调用之后添加任何初始化。
        dsResult = _dsResult

    End Sub
    Private Sub RadGridView_Click(sender As Object, e As EventArgs) Handles RadGridView.Click

    End Sub

    Private Sub Result_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Me.RadDropDownList1.Items.Clear()

        'For index = 0 To CheckFuncListChecked.Count - 1
        '    If CheckFuncListChecked(index) = func_CheckDrawingProp Then
        '        ' "图面属性_" 
        '        For I = 0 To dsOutput.Tables.Count - 1
        '            If dsOutput.Tables(I).TableName.StartsWith("图面属性_") Then
        '                Me.RadDropDownList1.Items.Add(dsOutput.Tables(I).TableName)
        '            End If
        '        Next
        '    Else
        '        Me.RadDropDownList1.Items.Add(CheckFuncListChecked(index))
        '    End If

        'Next
        For Each tb As DataTable In dsResult.Tables
            Me.RadDropDownList1.Items.Add(tb.TableName)
        Next

        Me.RadGridView.AllowAddNewRow = False
        Me.RadGridView.AllowDeleteRow = False
        Me.RadGridView.AllowEditRow = False
        Me.RadGridView.MultiSelect = False
        Me.RadGridView.AutoSizeColumnsMode = GridViewAutoSizeColumnsMode.Fill
        Me.RadGridView.SelectionMode = GridViewSelectionMode.FullRowSelect
    End Sub
    '调大单元格字体
    Private Sub RadGridView_CellFormatting(sender As Object, e As Telerik.WinControls.UI.CellFormattingEventArgs) Handles RadGridView.CellFormatting
        Dim newFont As New System.Drawing.Font(New System.Drawing.FontFamily("Calibri"), 12.0F, FontStyle.Regular)
        e.CellElement.Font = newFont
    End Sub


    Private Sub SPPID图上定位_Click(sender As Object, e As EventArgs) Handles SPPID图上定位.Click
        If Me.RadGridView.SelectedRows.Count = 1 Then
            Dim selectitem = Me.RadGridView.SelectedRows(0)
            Dim COL_ID = Me.RadGridView.Columns.GetColumnByFieldName("REPID")
            Dim COL_DWGNAME = Me.RadGridView.Columns.GetColumnByFieldName("所在图纸")

            If IsNothing(COL_ID) Or IsNothing(COL_DWGNAME) Then
                Exit Sub
            End If
            If COL_ID.Length = 0 Or COL_DWGNAME.Length = 0 Then
                Exit Sub
            End If

            Dim DWGName = selectitem.Cells("所在图纸").Value
            Dim DWGID As String = ""
            'Dim dtValveRe2 As New DataTable
            '            Dim sql1 = $"SELECT T.SP_ID,T.SP_MODELITEMID,T3.ITEMTAG,T4.SP_MODELITEMID RUN1ID,T5.SP_MODELITEMID RUN2ID
            'FROM xxxSchemaName.T_REPRESENTATION T
            'JOIN xxxSchemaName.T_PLANTITEM T3 ON T3.SP_ID = T.SP_MODELITEMID
            'LEFT JOIN xxxSchemaName.T_RELATIONSHIP R1 ON R1.SP_ITEM1ID = T.SP_ID
            'LEFT JOIN xxxSchemaName.T_REPRESENTATION T4 ON T4.SP_ID = R1.SP_ITEM2ID
            'LEFT JOIN xxxSchemaName.T_RELATIONSHIP R2 ON R2.SP_ITEM2ID = T.SP_ID
            'LEFT JOIN xxxSchemaName.T_DRAWING D ON D.SP_ID = T.SP_DRAWINGID
            'LEFT JOIN xxxSchemaName.T_REPRESENTATION T5 ON T5.SP_ID = R2.SP_ITEM1ID
            'WHERE T.REPRESENTATIONTYPE = '13' AND T.FILENAME NOT IN ('\Instrumentation\Signal Line\Pneumatic-SEG.sym','\Instrumentation\Signal Line\Capillary-SEG.sym','\Instrumentation\Signal Line\Electric-SEG.sym',
            ''\Instrumentation\Signal Line\Guided Electromagnetic-SEG.sym','\Instrumentation\Signal Line\Hydraulic-SEG.sym',
            ''\Instrumentation\Signal Line\Mechanical Link-snec.sym','\Instrumentation\Signal Line\Software Link-SEG.sym','\Instrumentation\Signal Line\Undefined-snec.sym','\Instrumentation\Signal Line\Unguided Electromagnetic-SEG.sym') AND
            'D.NAME = '{DWGName}'"
            'MyPIDConn.PIDReadDataByDBA(MyPIDConn.PIDPlant_DBNAME, MyPIDConn.ActivePlantPIDApp_User, sql1, dtValveRe2)
            Dim SPID = selectitem.Cells("REPID").Value.ToString() '分支的repid，或者阀门symbol的repid
            Dim SPID3 = selectitem.Cells("断点1侧RUNID").Value.ToString() '管子的spid
            Dim SPID4 = selectitem.Cells("断点2侧RUNID").Value.ToString() '管子的spid
            Dim remark = selectitem.Cells("备注").Value.ToString() '备注"] = "此处的元件两侧，有不必要的打断。";
            'Dim ColumnName1 As String = "SP_ID"
            'Dim FilterExpression As String = $"{ColumnName1} = '{SPID}'"
            'Dim FoundRows() As DataRow = dtValveRe2.Select(FilterExpression)
            Dim RealRepIdOrSPID As String = ""

            If remark = "此处的元件两侧，有不必要的打断。" Then
                RealRepIdOrSPID = SPID '阀门的打断，高亮阀门本身即可
            ElseIf remark = "此处有不必要的打断。" Then
                If Not String.IsNullOrEmpty(SPID4) Then '管子的打断，需要高亮断点2侧的管子
                    RealRepIdOrSPID = SPID4
                ElseIf Not String.IsNullOrEmpty(SPID3) Then
                    RealRepIdOrSPID = SPID3
                Else
                    RealRepIdOrSPID = SPID
                End If
                '意思是某个管子的SPID？????????????????????????????????????????????????????你确定能跳？
            End If
            Try

                ' initialize the PID Object Manager
                'Dim activProj As LMActiveProject
                'activProj = ds.GetActiveProject()
                'Dim plitem As LMPlantItem
                'plitem = ds.GetPlantItem(SPID.ToString)
                Dim radApp As Interop.RAD2D.Application
                Dim pidAutoApp As InteropPidAuto.Application

                'pidAutoApp = CreateObject("PIDAutomation.Application")

                pidAutoApp = New InteropPidAuto.Application()

                pidAutoApp.Activate()

                radApp = GetObject(, "SmartPlantPID.Application").radapplication
                Dim dtRep As New DataTable
                Dim Sql = $"select sp_id from xxxSchemaName.t_drawing t where t.name='{DWGName}'"
                MyPIDConn.PIDReadDataByDBA(MyPIDConn.PIDPlant_DBNAME, MyPIDConn.ActivePlantPIDApp_User, Sql, dtRep)

                Dim curDrawing As InteropPidAuto.Drawing

                If dtRep.Rows.Count > 0 Then ' And pidAutoApp.ActiveDrawing.Name.Replace(".pid", "") = DWGName Then
                    Dim found = False
                    For Each openDwg As InteropPidAuto.Drawing In pidAutoApp.Drawings
                        If openDwg.Name.Replace(".pid", "") = DWGName Then
                            openDwg.Activate()
                            curDrawing = pidAutoApp.ActiveDrawing
                            found = True
                        End If
                    Next
                    'For Each openDwg As Interop.RAD2D.Document In radApp.Documents
                    '    If openDwg.Name.Replace(".pid", "") = DWGName Then
                    '        openDwg.Activate()
                    '        found = True
                    '    End If
                    'Next
                    If Not found Then
                        curDrawing = pidAutoApp.Drawings.OpenDrawing(DWGName)
                        'MessageBox.Show($"请在P&ID中，事先打开{DWGName}该图纸")
                        'Exit Sub
                    End If
                    DWGID = dtRep.Rows(0)(0).ToString

                    Sql = $"select graphicoid from xxxSchemaName.t_Representation t
join xxxSchemaName.t_connector c on c.sp_id = t.sp_id
where t.sp_modelitemid='{RealRepIdOrSPID}' and t.sp_drawingid='{DWGID}'and (c.SP_ConnectItem1ID='{SPID}' OR c.SP_ConnectItem2ID='{SPID}')"
                    dtRep.Reset()
                    MyPIDConn.PIDReadDataByDBA(MyPIDConn.PIDPlant_DBNAME, MyPIDConn.ActivePlantPIDApp_User, Sql, dtRep)

                    If dtRep.Rows.Count = 0 Then '阀门的情况,id可能本来就不是modelitem
                        dtRep.Reset()
                        Sql = $"select graphicoid from xxxSchemaName.t_Representation t where t.sp_id='{RealRepIdOrSPID}' and t.sp_drawingid='{DWGID}'"
                        MyPIDConn.PIDReadDataByDBA(MyPIDConn.PIDPlant_DBNAME, MyPIDConn.ActivePlantPIDApp_User, Sql, dtRep)
                    End If

                    If dtRep.Rows.Count > 0 Then

                        '' deselect anything the user may have selected, this will ensure we "fit" nothing but the drawing view
                        '' comment out the following line, if you just want to Fit to the active Select Set
                        pidAutoApp.ActiveSelectSet.RemoveAll()

                        'Debug.Print(radApp.ActiveDocument.ActiveSheet.Name)
                        pidAutoApp.ActiveSelectSet.Add(radApp.ActiveDocument.ActiveSheet.DrawingObjects("Symbol2d " & dtRep.Rows(0)(0).ToString)) ' WORKS !!!  plitem.AsLMModelItem.Representations.Nth(1)



                        ' for Fit view to Select Set, there are a couple of options...
                        Dim intOption As Integer
                        intOption = 2
                        Select Case (intOption)
                            Case 1 ' WORKS, but uses a hard-coded path to a command macro
                                ' the radApp object also has the RunMacro method...
                                pidAutoApp.RunMacro("C:\Program Files (x86)\SmartPlant\P&ID Workstation\Bin\PidViewCmds.dll")
                            Case 2 ' WORKS, in SPPID 2014...
                                radApp.RunCommand(40068)
                        End Select
                    End If
                Else

                End If
            Catch ex As Exception

            End Try

        End If
    End Sub

    ''' <summary>
    ''' 根据pid数据库里的OID，找到ssk里的对象
    ''' </summary>
    ''' <param name="radApp"></param>
    ''' <param name="rep"></param>
    ''' <returns></returns>
    Private Function GetRadGraphic(radApp As Interop.RAD2D.Application, rep As LMRepresentation) As Object  ' 
        ' "xxx " gets replaced by RAD/SmartSketch object type, like "Symbol2d "; GraphicOID is the RAD object's Key value
        GetRadGraphic = radApp.ActiveDocument.ActiveSheet.DrawingObjects("Symbol2d " & rep.Attributes("GraphicOID").Value) '
    End Function

    Private Sub RadDropDownList1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles RadDropDownList1.SelectedIndexChanged
        'Me.RadDropDownList1.Items.Add(dsOutput.Tables(I).TableName)
        Dim tbName = Me.RadDropDownList1.SelectedItem

        Me.RadGridView.DataSource = Nothing
        If dsResult.Tables.Contains(tbName) Then
            Me.RadGridView.DataSource = dsResult.Tables(tbName)
        End If

    End Sub
End Class